package center

import (
	"bytes"
	"compress/gzip"
	"compress/lzw"
	"encoding/binary"
	"errors"
	"io"
	"log"
	"reflect"
)

func byteToInt(data []byte, integer interface{}) error {
	data_buf := bytes.NewBuffer(data)
	if d := reflect.ValueOf(integer); d.Kind() != reflect.Ptr {
		return errors.New("invalid int pointer type")
	}
	err := binary.Read(data_buf, binary.BigEndian, integer)
	return err
}

func int32ToByte(v int32) (out []byte) {
	out = make([]byte, 4)
	out[0] = byte(v >> 24)
	out[1] = byte((v << 8) >> 24)
	out[2] = byte((v << 16) >> 24)
	out[3] = byte((v << 24) >> 24)
	return out
}

func int16ToByte(v int16) (out []byte) {
	out = make([]byte, 2)
	out[0] = byte(v >> 8)
	out[1] = byte((v << 8) >> 8)
	return out
}

func byteToInt32(in []byte) int32 {
	return int32(in[0])<<24 + int32(in[1])<<16 + int32(in[2])<<8 + int32(in[3])
}

func byteToInt16(in []byte) int16 {
	return int16(in[0])<<8 + int16(in[1])
}
func bytesTostring(in []byte) string {
	var cnt int32
	for key, _ := range in {
		if in[key] != 0 {
			cnt = cnt + 1
		} else {
			break
		}
	}
	return string(in[0:cnt])
}
func strToLZW(src string) string {
	log.Printf("SRC: %s, Len: %d\n", src, len(src))

	var compressed_data bytes.Buffer
	dst := lzw.NewWriter(&compressed_data, lzw.MSB, 2)

	defer dst.Close()
	length, err := dst.Write([]byte(src))
	if err != nil {
		log.Print(err)
	}

	if length != len(src) {
		log.Print("Write error\n")
		return ""
	}

	out_str := compressed_data.String()
	log.Printf("DST: %s, Len: %d\n", out_str, len(out_str))
	return out_str
}

func strToGZip(src string) string {
	log.Printf("SRC: %s, Len: %s\n", src, len(src))
	compressed_data := new(bytes.Buffer)
	gz := gzip.NewWriter(compressed_data)
	defer gz.Close()
	gz.Write([]byte(src))
	out_str := compressed_data.String()
	log.Printf("DST: %s, Len: %d\n", out_str, len(out_str))

	r, _ := gzip.NewReader(compressed_data)
	decompressed_data := new(bytes.Buffer)
	io.Copy(decompressed_data, r)
	defer r.Close()
	destr := decompressed_data.String()
	log.Printf("DST: %s, Len: %d\n", destr, len(destr))

	return out_str
}

func gZipToStr() {

}
